<?php
/* 
 * CRMBaseController File
 *
 * @link http://riedel-st.de
 * @author Stefan Riedel <sr@riedel-st.de>
*/

/**
 * Description of CRMBaseController
 *
 * @author Stefan Riedel
 */
class CRMBaseController extends CController {
	
	const PAGE_SIZE = 10;
	
	protected static $_blocks = array();
	
	public function blocks($position) {
		if(self::$_blocks === array()) {
			$this->_initBlocks ();
		} 
		if(isset(self::$_blocks[$position]) && !empty(self::$_blocks[$position])) {
			foreach(self::$_blocks[$position] as $block) {
				$this->widget($block['file']);
			}
		}
	}
	/**
	 * innitialisiert und cached die blöcke
	 */
	protected function _initBlocks() {
		$blocks = new Blocks();
		$blocksItems = $blocks->findAll();
		if($blocksItems) {
			foreach($blocksItems as $block) {
				self::$_blocks[$block->blocks_position][] = array(
					'header' => $block->blocks_header,
					'footer' => $block->blocks_footer,
					'file' => $block->blocks_file,
				);
			}
		}
		else {
			self::$_blocks = array(false);
		}
	}

	
    /**
     *
     * Checks if the user has acces to fire this action
     *
     * @param string $action The fired action
     * @return bool true if the user has access false if not
     */
    protected function beforeAction($action) {
        $module = (null !== $this->module) ? $this->module->id : '';
        $access =  ucfirst($module).ucfirst($this->id).ucfirst($this->action->id);
        if(in_array($access, $this->allowedAccess())) {
            return true;
        }
        /**
         * @todo parameter - post/get mit einbeziehen, denn können wir auch bizRules benutzen
         */
        if(!Yii::app()->user->checkAccess($access) && !Yii::app()->user->isGuest) {
            Yii::app()->request->redirect(Yii::app()->createUrl(Yii::app()->urlManager->getRule('notAllowed')));
            return false;
        }
        elseif(!Yii::app()->user->checkAccess($access) && Yii::app()->user->isGuest) {
            Yii::app()->request->redirect(Yii::app()->createUrl(Yii::app()->user->loginUrl));
            return false;
        }
        else {
            return true;
        }
    }

    protected function allowedAccess() {
        return array('CoreUserLogin', 'CoreUserLogout', 'CoreErrorNotAllowed', 'CoreUserCaptcha');
    }
}
?>
